﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

namespace Finbook.Mvc.Infrastructure
{
    public class AuthorizationHttpClientHandler
        : HttpClientHandler
    {
        //private readonly string _authorizationCode;
        private readonly Func<string> _getTokenFunc;
        //public AuthorizationHttpClientHandler(string authorizationCode)
        //{
        //    _authorizationCode = authorizationCode;
        //}
        public AuthorizationHttpClientHandler(Func<string> getTokenFunc)
        {
            _getTokenFunc = getTokenFunc;
        }
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var auth = request.Headers.Authorization;
            if (auth!=null)
            {
                //request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(auth.Scheme, _authorizationCode);
                request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(auth.Scheme, _getTokenFunc());
            }
            return base.SendAsync(request, cancellationToken);
        }
    }
}
